package com.ysh.servlet;

import com.github.pagehelper.PageInfo;
import com.ysh.domain.Student;
import com.ysh.domain.User;
import com.ysh.service.StudentService;
import com.ysh.service.UserService;
import com.ysh.service.impl.StudentServiceImpl;
import com.ysh.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/*
    用户登录Controller层
 */
@WebServlet("/user")
public class UserServlet extends HttpServlet {
    // 创建业务层对象
    private UserService userService = new UserServiceImpl();
    private StudentService studentService = new StudentServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 统一编码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        // 获取请求中method的值，执行不同处理
        String method = req.getParameter("method");
        if ("login".equals(method)) {
            login(req, resp);
        }
        if ("findAll".equals(method)) {
            findAll(req, resp);
        }
    }

    // 遍历查询所有学生信息
    private void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*
            分页相关数据查询
         */
        // 获取当前页码
        String pageN = req.getParameter("pageNum");
        Integer pageNum = null;
        if (pageN != null && !"".equals(pageN)) {
            pageNum = Integer.parseInt(pageN);
        }
        // 对首页进行处理
        if (pageNum == null) {
            pageNum = 1;
        }


        // 遍历所有学生信息信息
        List<Student> list = studentService.findAll(pageNum);
        // 对查询的数据进行分页处理
        PageInfo<Student> pageInfo = new PageInfo<>(list);
        // 将数据存入request作用域
        // req.setAttribute("list", list);
        req.setAttribute("pageInfo",pageInfo);
        // 转发到主页面
        req.getRequestDispatcher("/main.jsp").forward(req, resp);

    }

    // 登录操作
    private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 从页面获取登录用户名和密码数据
        String username = req.getParameter("username");
        String pwd = req.getParameter("pwd");
        // 调用service处理，得到返回结果
        User user = userService.login(username, pwd);
        if (user != null) {
            // resp.getWriter().write("登录成功！");
            // 跳转到查询所有
            req.getRequestDispatcher("user?method=findAll").forward(req, resp);
        }
    }
}
